<template>
	<view class="index-container">
		<!-- 地址栏 - 增加渐变背景和图标间距 -->
		<view class="address-bar gradient-bg" @click="changeAddress">
			<uni-icons type="location-filled" size="20" color="#fff"></uni-icons>
			<text class="address-text">{{ currentAddress || '点击设置收货地址' }}</text>
			<uni-icons type="arrowright" size="16" color="#fff"></uni-icons>
		</view>

		<!-- 搜索栏 - 增加圆角和阴影 -->
		<view class="search-bar">
			<uni-search-bar radius="30" :placeholder="searchPlaceholder" @confirm="debounceSearch"
				@input="handleSearchInput" @clear="handleClearSearch" :showCancel="false" bgColor="#ffffff"
				placeholderColor="#999" class="search-box">
				<template v-slot:searchIcon>
					<uni-icons type="search" size="18" color="#666"></uni-icons>
				</template>
			</uni-search-bar>

			<!-- 搜索历史 - 优化弹出层样式 -->
			<view v-if="showHistory && searchHistory.length > 0" class="search-history card-shadow">
				<view class="history-header">
					<text class="title">历史搜索</text>
					<uni-icons type="trash" size="20" @click="clearSearchHistory" color="#666"></uni-icons>
				</view>
				<scroll-view scroll-y class="history-scroll">
					<view v-for="(item, index) in searchHistory" :key="index" class="history-item"
						@click="selectHistoryItem(item)">
						{{ item }}
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 轮播图 - 增加指示点样式 -->
		<swiper class="swiper" :autoplay="true" :interval="3000" :circular="true" :indicator-dots="true"
			indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#ff6700">
			<swiper-item v-for="(item, index) in swiperList" :key="index" class="swiper-item">
				<image class="swiper-image" :src="item.image" mode="aspectFill" :lazy-load="true" />
				<view v-if="!item.image" class="image-placeholder">
					<uni-icons type="picture" size="40" color="#ccc"></uni-icons>
				</view>
			</swiper-item>
		</swiper>

		<!-- 分类导航 - 优化布局和动效 -->
		<view class="category-section card-shadow">
			<view class="section-title">
				<text class="title">全部分类</text>
				<text class="more">全部</text>
			</view>
			<scroll-view scroll-x class="category-scroll" show-scrollbar="false">
				<view v-for="(item, index) in firstCategories" :key="item.typeFirstId" class="category-item"
					@click="debounceNav(item)">
					<image :src="getCategoryIcon(item.nameFirst)" class="category-icon" mode="aspectFill" />
					<text class="category-name">{{ item.nameFirst }}</text>
				</view>
			</scroll-view>
		</view>

		<!-- 限时抢购 - 增加倒计时和价格样式 -->
		<view class="flash-sale card-shadow">
			<view class="flash-header">
				<view class="title-wrapper">
					<text class="title">限时抢购</text>
					<view class="countdown-badge">
						<text class="countdown-text">距结束</text>
						<uni-countdown 
							:show-day="false" 
							:hour="6" 
							:minute="0" 
							:second="0"
							color="#ff0036" 
							splitor-color="#ff0036"
							background-color="transparent"
							class="custom-countdown"
						/>
					</view>
				</view>
				<text class="more" @click="debounceViewMore">查看更多 ></text>
			</view>
			
			<scroll-view scroll-x class="goods-scroll" show-scrollbar="false">
				<view 
					v-for="(item, index) in 3" 
					:key="index"
					class="goods-item"
				>
					<view class="goods-card">
						<view class="corner-tag">爆款</view>
						<image 
							src="/static/images/flash-sale-demo.jpg" 
							class="goods-image"
							mode="aspectFill"
							lazy-load
						/>
						<view class="price-section">
							<view class="price-wrapper">
								<text class="current-price">¥99</text>
								<text class="original-price">¥199</text>
							</view>
							<view class="buy-btn">立即抢购</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import {
		getGoodsCategories
	} from '@/api/goods';
	import {
		saveSearchHistory,
		getSearchHistory
	} from '@/api/search';
	import {
		request
	} from '@/utils/request.js';
	import {
		debounce
	} from '@/utils/common.js'; // 新增防抖工具

	export default {
		data() {
			return {
				currentAddress: "",
				searchPlaceholder: "搜索商品",
				swiperList: [{
						image: "/static/images/fruit.jpg",
						link: ""
					},
					{
						image: "/static/images/meat.jpg",
						link: ""
					},
					{
						image: "/static/images/egg.jpg",
						link: ""
					}
				],
				firstCategories: [],
				// 搜索历史相关
				showHistory: false,
				searchHistory: [],
				userId: 3, // 固定用户ID
				searchKeyword: ''
			};
		},
		async created() {
			await this.loadCategories();
			await this.loadSearchHistory();
			this.setSearchPlaceholder();
			await this.loadDefaultAddress(); // 加载默认地址
			// 初始化防抖方法
			this.debounceSearch = debounce(this.handleSearch, 500);
			this.debounceNav = debounce(this.goToCategory, 300);
			this.debounceViewMore = debounce(this.viewMore, 300);
		},
		methods: {
			// 加载分类数据
			async loadCategories() {
				try {
					const res = await getGoodsCategories();
					if (res.code === 200) {
						// 提取一级分类(去重)
						const firstCategoriesMap = new Map();
						res.data.forEach(item => {
							if (!firstCategoriesMap.has(item.typeFirstId)) {
								firstCategoriesMap.set(item.typeFirstId, {
									typeFirstId: item.typeFirstId,
									nameFirst: item.nameFirst
								});
							}
						});
						this.firstCategories = Array.from(firstCategoriesMap.values());
					}
				} catch (error) {
					console.error('加载分类失败:', error);
				}
			},

			// 加载搜索历史
			async loadSearchHistory() {
				try {
					const res = await getSearchHistory(this.userId);
					if (res.code === 200 && res.data) {
						this.searchHistory = res.data;
					}
				} catch (error) {
					console.error('加载搜索历史失败:', error);
				}
			},

			// 保存搜索历史
			async saveSearchHistory(keyword) {
				try {
					// 去重处理
					const index = this.searchHistory.indexOf(keyword);
					if (index !== -1) {
						this.searchHistory.splice(index, 1);
					}
					this.searchHistory.unshift(keyword);

					// 限制数量
					if (this.searchHistory.length > 10) {
						this.searchHistory = this.searchHistory.slice(0, 10);
					}

					await saveSearchHistory(this.userId, keyword);
				} catch (error) {
					console.error('保存搜索历史失败:', error);
				}
			},

			// 设置搜索框placeholder
			setSearchPlaceholder() {
				const placeholders = [
					"搜索新鲜水果",
					"搜索优质肉类",
					"搜索当季蔬菜",
					"搜索特价商品"
				];
				this.searchPlaceholder = placeholders[Math.floor(Math.random() * placeholders.length)];
			},

			// 点击地址跳转到地址管理页面
			changeAddress() {
				uni.navigateTo({
					url: '/pages/myAddress/myAddress'
				});
			},

			// 加载默认地址
			async loadDefaultAddress() {
				try {
					const res = await request({
						url: "address/queryAddressByUserId",
						method: "GET"
					});

					if (res.code === 200 && res.data && res.data.length > 0) {
						// 查找默认地址
						const defaultAddress = res.data.find(item => item.defaultAddress === 1);
						if (defaultAddress) {
							// 组合完整地址：城市 + 区县 + 详细地址
							const cityName = defaultAddress.cityName || '';
							const districtName = defaultAddress.districtName || '';
							this.currentAddress = `${cityName}${districtName}${defaultAddress.address}`;
						} else {
							// 如果没有默认地址，使用第一个地址
							const firstAddress = res.data[0];
							const cityName = firstAddress.cityName || '';
							const districtName = firstAddress.districtName || '';
							this.currentAddress = `${cityName}${districtName}${firstAddress.address}`;
						}
					}
				} catch (error) {
					console.error('加载地址失败:', error);
					this.currentAddress = '加载地址失败，请点击重试';
				}
			},

			// 处理搜索
			async handleSearch(e) {
				const keyword = e.value || e;
				if (!keyword) return;

				// 保存搜索历史
				await this.saveSearchHistory(keyword);

				uni.navigateTo({
					url: `/pages/category/category?keyword=${keyword}`
				});
			},

			// 选择历史记录
			selectHistoryItem(item) {
				this.searchKeyword = item;
				this.handleSearch(item);
				this.showHistory = false;
			},

			// 清空搜索历史
			async clearSearchHistory() {
				try {
					this.searchHistory = [];
					uni.showToast({
						title: '已清空搜索历史',
						icon: 'success'
					});
				} catch (error) {
					console.error('清空搜索历史失败:', error);
				}
			},

			// 搜索框失去焦点
			handleSearchBlur() {
				setTimeout(() => {
					this.showHistory = false;
				}, 200);
			},

			// 搜索输入处理
			handleSearchInput(e) {
				this.searchKeyword = e.value;
			},

			// 清除搜索
			handleClearSearch() {
				this.searchKeyword = '';
			},

			// 获取分类图标
			getCategoryIcon(name) {
				const icons = {
					'肉类': '/static/images/meat.jpg',
					'蛋类': '/static/images/egg.jpg',
					'蔬菜': '/static/images/vegetable.jpg',
					'水果': '/static/images/fruit.jpg'
				};
				return icons[name] || '/static/images/category.jpg';
			},

			// 跳转到分类页（携带一级分类ID）
			goToCategory(category) {
				uni.switchTab({
					url: '/pages/category/category',
					success: () => {
						// 可以通过全局变量或vuex传递参数
						uni.$emit('categoryChange', {
							typeFirstId: category.typeFirstId
						});
					}
				});
			},

			// 查看更多抢购
			viewMore() {
				uni.showToast({
					title: '限时抢购',
					icon: 'none'
				});
				uni.switchTab({
					url: '/pages/timesale/timesale'
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	/* 新增颜色变量 */
	$primary-color: #ff6700;
	$danger-color: #ff0036;
	$text-dark: #333;
	$text-light: #666;
	$border-color: #eee;

	.index-container {
		padding-bottom: 20rpx;
		background: #f8f8f8;
	}

	/* 地址栏 - 渐变背景 */
	.address-bar {
		display: flex;
		align-items: center;
		padding: 24rpx 32rpx;
		background: linear-gradient(90deg, $primary-color, #ff8c00);
		color: #fff;

		.address-text {
			flex: 1;
			margin: 0 20rpx;
			font-size: 28rpx;
			// @include text-ellipsis;
		}
	}

	/* 搜索栏 - 卡片阴影 */
	.search-bar {
		padding: 24rpx 32rpx;
		position: relative;

		.search-box {
			border-radius: 48rpx !important;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		}
	}

	/* 分类导航 - 卡片式设计 */
	.category-section {
		margin: 24rpx 32rpx;
		padding: 24rpx;
		background: #fff;
		border-radius: 16rpx;

		.section-title {
			display: flex;
			justify-content: space-between;
			margin-bottom: 24rpx;

			.title {
				font-size: 32rpx;
				font-weight: 600;
				color: $text-dark;
			}
		}

		.category-scroll {
			white-space: nowrap;

			.category-item {
				display: inline-flex;
				flex-direction: column;
				align-items: center;
				margin-right: 40rpx;

				.category-icon {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					margin-bottom: 12rpx;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
				}

				.category-name {
					font-size: 24rpx;
					color: $text-light;
				}
			}
		}
	}

	/* 通用卡片阴影 */
	.card-shadow {
		box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.08);
		border-radius: 16rpx;
	}

	/* 文本截断混合宏 */
	@mixin text-ellipsis {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/* 搜索历史样式 */
	.search-history {
		position: absolute;
		top: 100%;
		left: 30rpx;
		right: 30rpx;
		background-color: #fff;
		border-radius: 0 0 10rpx 10rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
		z-index: 999;
		padding: 20rpx;
		margin-top: -10rpx;
	}

	.history-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx;
		font-size: 14px;
		color: #666;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 10rpx;
	}

	.history-list {
		display: flex;
		flex-wrap: wrap;
	}

	.history-item {
		background-color: #f5f5f5;
		padding: 10rpx 20rpx;
		margin: 10rpx;
		border-radius: 30rpx;
		font-size: 12px;
		color: #333;
	}

	.swiper {
		height: 300rpx;
		margin: 0 30rpx;
		border-radius: 10rpx;
		overflow: hidden;

		.swiper-image {
			width: 100%;
			height: 100%;
		}
	}

	.flash-sale {
		margin: 24rpx 32rpx;
		padding: 24rpx;
		background: #fff;

		.flash-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 32rpx;
			
			.title-wrapper {
				display: flex;
				align-items: baseline;
			
				.title {
					font-size: 36rpx;
					font-weight: 600;
					color: $danger-color;
					margin-right: 24rpx;
				}
				
				.countdown-badge {
					display: flex;
					align-items: center;
					flex-wrap: nowrap; // 禁止换行
					white-space: nowrap; // 关键修复
			
					.countdown-text {
						margin-right: 8rpx;
					}
			
					.custom-countdown {
						::v-deep .uni-countdown {
							display: inline-flex !important;
							align-items: center;
							
							&__number,
							&__splitor {
								display: inline-block;
								line-height: 1;
							}
						}
					}
				}
			}
			
			.more {
				font-size: 26rpx;
				color: $text-light;
			}
		}

		.goods-scroll {
			white-space: nowrap;
			padding-bottom: 16rpx; // 滚动条间距

			.goods-item {
				display: inline-block;
				width: 360rpx;
				margin-right: 24rpx;

				.goods-card {
					position: relative;
					border-radius: 16rpx;
					overflow: hidden;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

					.corner-tag {
						position: absolute;
						top: 0;
						left: 0;
						padding: 8rpx 16rpx;
						background: $danger-color;
						color: #fff;
						font-size: 20rpx;
						border-radius: 0 0 16rpx 0;
						z-index: 2;
					}

					.goods-image {
						width: 100%;
						height: 260rpx;
						background: #f5f5f5;
					}
					
					.price-section {
						display: flex;
						justify-content: space-between;
						align-items: flex-end;
						padding: 16rpx;
					}
					
					.price-wrapper {
						flex: 1;
						padding: 16rpx;
						.current-price {
							font-size: 32rpx;
							color: $danger-color;
							font-weight: bold;
						}
						
						.original-price {
							font-size: 24rpx;
							color: $text-light;
							text-decoration: line-through;
							margin-left: 12rpx;
						}
					}
					
					.buy-btn {
						position: static; // 移除绝对定位
						margin-left: 20rpx;
						padding: 8rpx 24rpx;
						background: $danger-color;
						color: #fff;
						font-size: 24rpx;
						border-radius: 40rpx;
						white-space: nowrap;
					}
				}

				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
</style>